/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gee.util;

/**
 *
 * @author CoCo
 */
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VolumeControl;

public class SoundUtil {

	private Player[] play;
	private VolumeControl[] vControl;
	private int musicID;

	public SoundUtil() {
		play = new Player[3];
		vControl = new VolumeControl[3];
	}

	/**
	 * 初始化声音资源
	 * 
	 * @param musicID
	 *            音乐的编号
	 */
	public void init(int musicID) {
		this.musicID = musicID;
		InputStream is = this.getClass().getResourceAsStream(
				"/res/music/" + musicID + ".mid");
		try {
			play[musicID] = Manager.createPlayer(is, "audio/midi");
			play[musicID].realize();
			play[musicID].prefetch();
			vControl[musicID] = (VolumeControl) play[musicID]
					.getControl("VolumeControl");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MediaException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 播放音乐
	 * 
	 */
	public void play(int i) {
		if (play[i] != null) {
			try {
				play[i].setLoopCount(-1);
				play[i].start();
			} catch (MediaException e) {
				e.printStackTrace();
			}
		}
	}

	public int getPlayer() {
		// for(int i = 0;i<play.length;i++)
		// if(play[musicID]!=null)
		return musicID;

	}

	public void play(int i, int time) {
		if (play[i] != null) {
			try {
				play[i].realize();
				play[i].setLoopCount(time);
				play[i].start();
			} catch (MediaException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 设置音量
	 * 
	 * @param level
	 *            音量
	 */
	public void setVolume(int ID, int level) {
		vControl[ID].setLevel(level);
	}

	/**
	 * 暂停播放
	 * 
	 */
	public void pause(int ID) {
		vControl[ID].setLevel(0);
	}

	public void replay(int ID) {
		vControl[ID].setLevel(100);
	}

	/**
	 * 停止播放
	 * 
	 */
	public void stop(int i) {
		try {
			play[i].stop();
			play[i].close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		play[i] = null;
		vControl[i] = null;
	}
}
